<?php
use common\core\modularity\ModuleServiceInterface;
use yii\base\InvalidParamException;
use yii\helpers\VarDumper;
use yii\helpers\Url;
use yii\data\Pagination;

/**
 * YiiCenter Shortcuts
 * -----
 * This file is just an example and a place where you can add your own shortcuts,
 * it doesn't pretend to be a full list of available possibilities
 * -----
 */

/**
 *
 * @return int|string
 */
function getMyId()
{
    return Yii::$app->user->getId();
}

/**
 *
 * @param string $view
 * @param array $params
 * @return string
 */
function render($view, $params = [])
{
    return Yii::$app->controller->render($view, $params);
}

/**
 *
 * @param
 *            $url
 * @param int $statusCode
 * @return \yii\web\Response
 */
function redirect($url, $statusCode = 302)
{
    return Yii::$app->controller->redirect($url, $statusCode);
}

/**
 *
 * @param $form \yii\widgets\ActiveForm
 * @param
 *            $model
 * @param
 *            $attribute
 * @param array $inputOptions
 * @param array $fieldOptions
 * @return string
 */
function activeTextinput($form, $model, $attribute, $inputOptions = [], $fieldOptions = [])
{
    return $form->field($model, $attribute, $fieldOptions)->textInput($inputOptions);
}

function getApp()
{
    return Yii::$app;
}

function getView()
{
    $app = getApp();
    return $app->getView();
}

function getRequest()
{
    $app = getApp();
    return $app->request;
}

function getResponse()
{
    $app = getApp();
    return $app->response;
}

function getBaseUrl($url = null)
{
    $app = getApp();
    $baseUrl = $app->request->getBaseUrl();
    if ($url !== null)
    {
        $baseUrl .= $url;
    }
    return $baseUrl;
}

function getHomeUrl($url = null)
{
    $app = getApp();
    $homeUrl = $app->getHomeUrl();
    if ($url !== null)
    {
        $homeUrl .= $url;
    }
    return $homeUrl;
}

function getWebUrl($url = null)
{
    $webUrl = Yii::getAlias('@web');
    if ($url !== null)
    {
        $webUrl .= $url;
    }
    return $webUrl;
}

function getWebPath($path = null)
{
    $webPath = Yii::getAlias('@webroot');
    if ($path !== null)
    {
        $webPath .= $path;
    }
    return $webPath;
}

function getAppParam($key, $defaultValue = null)
{
    $app = getApp();
    if (array_key_exists($key, $app->params))
    {
        return $app->params[$key];
    }
    return $defaultValue;
}

function setAppParam($array)
{
    $app = getApp();
    foreach ($array as $key => $value)
    {
        $app->params[$key] = $value;
    }
}

function getViewParam($key, $defaultValue = null)
{
    $app = getApp();
    $view = $app->getView();
    if (array_key_exists($key, $view->params))
    {
        return $view->params[$key];
    }
    return $defaultValue;
}

function setViewParam($array)
{
    $app = getApp();
    $view = $app->getView();
    foreach ($array as $name => $value)
    {
        $view->params[$name] = $value;
    }
}

function hasGetValue($key)
{
    return isset($_GET[$key]);
}

function getGetValue($key, $default = NULL)
{
    if (hasGetValue($key))
    {
        return $_GET[$key];
    }
    return $default;
}

function hasPostValue($key)
{
    return isset($_POST[$key]);
}

function getPostValue($key, $default = NULL)
{
    if (hasPostValue($key))
    {
        return $_POST[$key];
    }
    return $default;
}

function getFlash($type,$default=null)
{
    $app = getApp();
    return $app->session->getFlash($type,$default);
}
function setFlash($type, $message)
{
    $app = getApp();
    $app->session->setFlash($type, $message);
}

function setWarningMessage($message)
{
    $app = getApp();
    $app->session->setFlash('warning', $message);
}

function setSuccessMessage($message)
{
    $app = getApp();
    $app->session->setFlash('success', $message);
}

function setErrorMessage($message)
{
    $app = getApp();
    $app->session->setFlash('error', $message);
}

function info($var, $category = 'application')
{
    $dump = VarDumper::dumpAsString($var);
    Yii::info($dump, $category);
}

function getUser()
{
    $app = getApp();
    return $app->user;
}

function getIdentity()
{
    $app = getApp();
    return $app->user->getIdentity();
}

function getIsGuest()
{
    $app = getApp();
    return $app->user->isGuest;
}

function checkIsGuest($loginUrl = null)
{
    $app = getApp();
    $isGuest = $app->user->isGuest;
    if ($isGuest)
    {
        if ($loginUrl == false)
        {
            return false;
        }
        if ($loginUrl == null)
        {
            $loginUrl = [
                'site/login'
            ];
        }
        return $app->getResponse()->redirect(Url::to($loginUrl), 302);
    }
    return true;
}

function checkAuth($permissionName, $params = [], $allowCaching = true)
{
    $app = getApp();
    return $app->user->can($permissionName, $params, $allowCaching);
}

function getDB()
{
    $app = getApp();
    return $app->db;
}

function createCommand($sql = null)
{
    $app = getApp();
    $db = $app->db;
    if ($sql !== null)
    {
        return $db->createCommand($sql);
    }
    return $db->createCommand();
}

function execute($sql)
{
    $app = getApp();
    $db = $app->db;
    $command = $db->createCommand($sql);
    return $command->execute();
}

function queryAll($sql)
{
    $app = getApp();
    $db = $app->db;
    $command = $db->createCommand($sql);
    return $command->queryAll();
}

function queryOne($sql)
{
    $app = getApp();
    $db = $app->db;
    $command = $db->createCommand($sql);
    return $command->queryOne();
}

function getPagedRows($query, $config = [])
{
    $countQuery = clone $query;
    $pages = new Pagination([
        'totalCount' => $countQuery->count()
    ]);
    if (isset($config['page']))
    {
        $pages->setPage($config['page'], true);
    }

    if (isset($config['pageSize']))
    {
        $pages->setPageSize($config['pageSize'], true);
    }

    $rows = $query->offset($pages->offset)->limit($pages->limit);

    if (isset($config['orderBy']))
    {
        $rows = $rows->orderBy($config['orderBy']);
    }
    $rows = $rows->all();

    $rowsLable = isset($config['rows']) ? $config['rows'] : 'rows';
    $pagesLable = isset($config['pager']) ? $config['pager'] : 'pager';

    $ret = [];
    $ret[$rowsLable] = $rows;
    $ret[$pagesLable] = $pages;

    return $ret;
}

function getService($id)
{
    $id = $id . 'Service';
    $component = \Yii::$app->get($id, true);
    if ($component instanceof ModuleServiceInterface) {
        return $component;
    }
    throw new InvalidParamException("get service:$id");
}

function getModularityService()
{
    return getService('modularity');
}

function getStorageService()
{
    return getService('storage');
}

function getSystemService()
{
    return getService('system');
}

function getCache($key)
{
    $cache = \Yii::$app->cache;
    return $cache->get($key);
}

function setCache($key, $value, $duration = 0, $dependency = null)
{
    $cache = \Yii::$app->cache;
    return $cache->set($key, $value, $duration, $dependency);
}

function deleteCache($key)
{
    $cache = \Yii::$app->cache;
    $cache->delete($key);
}

function flushCache()
{
    $cache = \Yii::$app->cache;
    $cache->flush();
}

/**
 * @param yii\db\ActiveQuery $query
 */
function varDumpQuerySql($query)
{
    VarDumper::dump($query->createCommand()->getRawSql());
}
